package com.starbaba.activityCommend.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.base.common.util.StringUtils;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.activityCommend.model.LoanActivityModel;
import com.starbaba.activityCommend.model.LoanAdvertModel;
import com.starbaba.activityCommend.model.LoanProductChannelModel;
import com.starbaba.activityCommend.service.LoanAdvertService;
import com.starbaba.channelmanager.model.Product;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.core.web.translate.TranslateVO;
import com.starbaba.loanActivity.view.LoanProductAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.redis.JedisUtils;
import com.starbaba.utils.LifeConstant;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;

@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class LoanAdvertAction extends BaseAction implements ModelDriven<LoanAdvertModel> {

	@SuppressWarnings("deprecation")
    final BaseDao dao = new BaseDao(Constant.POOL_LIFE);

	private LoanAdvertModel model;

	private LoanAdvertService service;

	private ArrayList<ControlLogCategory> logCategorysArrayList;
	
	@Autowired
	@Qualifier("loanAdvertServiceImpl")
	public void setService(LoanAdvertService service) {
		this.service = service;
	}

	@Override
	public LoanAdvertModel getModel() {
		if (model == null) {
			model = new LoanAdvertModel();
		}
		return model;
	}
    
	public String show() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		List<LoanProductChannelModel> listtemp= getChannelList();
		paramsMap.put("modelList", listtemp);
		List<LoanProductChannelModel> prdlist= getPrd();
		paramsMap.put("prdlist", prdlist);
		List<LoanActivityModel> activityList = getActivityIDList();
		paramsMap.put("activityList", activityList);
		
		try {
			List<Product> productList = getProductList();
			paramsMap.put("productList", productList);
			List<TranslateVO> advertiseList = LifeConstant.getSysCodeTranslate("advertise");
			paramsMap.put("advertises", advertiseList);
		} catch (Exception e) {
			LogService.error(e);
		}
		return SUCCESS;
	}
	
	/**
	 * 活动列表
	 */
	public void getActivityList() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		
		List<LoanProductChannelModel> listtemp= getChannelList();
		paramsMap.put("modelList", listtemp);
		
		List<LoanProductChannelModel> prdlist= getPrd();
		paramsMap.put("prdlist", prdlist);
		
		List<LoanActivityModel> activityList = getActivityIDList();
		paramsMap.put("activityList", activityList);
		
		List<LoanAdvertModel> advertList = service.getDataList(start, length, pageResponse, paramsMap);
		
		List<TranslateVO> advertiseList = null;
		Map<String ,String> advertiseMap = new HashMap<String, String>();
		try {
			advertiseList = LifeConstant.getSysCodeTranslate("advertise");
			for(TranslateVO vo : advertiseList) {
				advertiseMap.put(vo.getCode(), vo.getName());
			}
			for(LoanAdvertModel advert : advertList) {
				advert.setAdvert_space_name(advertiseMap.get(String.valueOf(advert.getAdvert_space())));
			}
		} catch (Exception e1) {
			LogService.error("读取贷款列表产品异常：",e1);
		}
		
		pageResponse.setAaData(advertList);
		pageResponse.setSEcho(pageRequest.getSEcho());

		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (IOException e) {
			LogService.error("下发贷款列表产品异常：",e);
		}
	}
	
	public String getInfo(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		String id = (String) paramsMap.get("id");
		
		LoanAdvertModel vo = new LoanAdvertModel();
		try {
			if(id != null)
				model = dao.get("select * from loan_advert where id =?", LoanAdvertModel.class, id);
			
			if(model == null){
				
				model = new LoanAdvertModel();
			}
			
			paramsMap.put("model", model);
		} catch (AppException e) {
			LogService.error(e);
		}
		
		List<LoanProductChannelModel> list= getChannelList();
		paramsMap.put("modelList", list);
		List<LoanActivityModel> activityList = getActivityIDList();
		paramsMap.put("activityList", activityList);
		try {
			List<Product> productList = getProductList();
			paramsMap.put("productList", productList);
			
			List<TranslateVO> advertiseList = LifeConstant.getSysCodeTranslate("advertise");
			paramsMap.put("advertises", advertiseList);
		} catch (Exception e) {
			LogService.error(e);
		}
		return SUCCESS;
	}
	
	/**
	 * 模板列表
	 * @return
	 * @throws Exception
	 */
	public List<LoanProductChannelModel> getChannelList() {
		
		String sql = "select channel_code,channel_name from comm_product_channel";
		try {
			List<LoanProductChannelModel> list = dao.list(sql, LoanProductChannelModel.class, new Object[] {});
			
			return list;
		} catch (AppException e) {
			LogService.error(e);
		}
		return null;
	}
	
	/**
	 * 模板列表
	 * @return
	 * @throws Exception
	 */
	public List<LoanProductChannelModel> getPrd() {
		
		String sql = "select name channel_name,prdid from comm_product_prdid";
		try {
			List<LoanProductChannelModel> list = dao.list(sql, LoanProductChannelModel.class, new Object[] {});
			
			return list;
		} catch (AppException e) {
			LogService.error(e);
		}
		return null;
	}
	
	/**
	 * 模板列表
	 * @return
	 * @throws Exception
	 */
	public List<LoanActivityModel> getActivityIDList() {
		
		String sql = "select id,name from loan_product_info";
		try {
			List<LoanActivityModel> list = dao.list(sql, LoanActivityModel.class, new Object[] {});
			
			return list;
		} catch (AppException e) {
			LogService.error(e);
		}
		return null;
	}
    
	public List<Product> getProductList() throws AppException {
		//在基础上添加产品列表
		String sql = " SELECT DISTINCT prdid AS code,name AS kindname FROM comm_product_prdid";
		Product p = new Product();
		p.setCode(0);
		p.setKindname("通用");
		List<Product> productList = dao.list(sql, Product.class);
		productList.add(p);
		return productList;
	}
	
	
	/**
	 * 编辑活动
	 * @return
	 * @throws Exception
	 */
	public String editActivity() throws Exception {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		String id = (String) paramsMap.get("id");
		if (!StringUtils.isEmpty(id)) {
			LoanAdvertModel vo = new LoanAdvertModel();
			try {
				String sql = "select c.id,c.platform,c.prdid,c.channel,c.position,c.exclude_channel,"
						+ "c.startTime,c.endTime, c.fixed_start_time, c.fixed_end_time, c.status,c.activity_id,c.suggest,c.ctime,c.utime,c.operator,c.remark,c.tag,c.advert_space,c.is_timer,c.redirect_type,c.upper_limit from loan_advert c where id=? ";
				model = dao.get(sql, LoanAdvertModel.class, id);
				if (model == null) {
					LogService.info("error: LoanAdvertAction#editActivity()---> model is null !!!");
				} else {
					LogService.info("Info: LoanAdvertAction#editActivity()---> model is not null !!!");
					LogService.info("Info: LoanAdvertAction#editActivity()---> ID=" + model.getId() + " " + "position=" + model.getPosition());
				}
				paramsMap.put("model", model);
			} catch (AppException e) {
				LogService.error(e);
			}
		}
		List<TranslateVO> advertiseList = LifeConstant.getSysCodeTranslate("advertise");
		paramsMap.put("advertises", advertiseList);
		
		List<LoanProductChannelModel> list = getChannelList();
		paramsMap.put("modelList", list);

		List<LoanProductChannelModel> prdlist = getPrd();
		paramsMap.put("prdlist", prdlist);

		List<LoanActivityModel> activityList = getActivityIDList();
		paramsMap.put("activityList", activityList);
		try {
			List<Product> productList = getProductList();
			paramsMap.put("productList", productList);
		} catch (AppException e) {
			LogService.error(e);
		}
		return SUCCESS;
	}
    
	
	/**
	 * 新增/编辑产品
	 * @throws ParseException
	 * @throws IOException
	 */
	public void saveActivity() throws ParseException, IOException {
		boolean isValidate = true;
		ResultJson resultJs = new ResultJson();
		JsonObject result = new JsonObject();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		
		if(isValidate){
			
			if (StringUtils.isEmpty(id)) { // 新增
				SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	            String date = tempFormat.format(new Date());
	            model.setCtime(date);
	            service.save(paramsMap, model);
				resultJs.msg = "保存成功";
			} else {// 更新
				try {
					service.update(paramsMap, model);
					resultJs.msg = "更新成功";
				} catch (Exception e) {
					LogService.error(e);
				}
			}
		}
		LoanProductAction.delRedis();
		try {
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			LogService.error(e);
		}
	}

    /**
     * 产品上线/下线
     * @throws NumberFormatException
     * @throws AppException
     */
	public void updateStatus() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String status = (String) paramsMap.get("status");
		try {
			String sql = "update loan_advert c set c.status = ? where c.id= ? ";
			dao.update(sql, status, Long.parseLong(id));
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "操作成功";
			result.add("result", resultJs.toJSON());
			LoanProductAction.delRedis();
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}
	 /**
     * 显示/不显示
     * @throws NumberFormatException
     * @throws AppException
     */
	public void delState() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		try {
			String sql = "update loan_advert c set c.show_state = 0 where c.id= ? ";
			dao.update(sql, Long.parseLong(id));
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "操作成功";
			result.add("result", resultJs.toJSON());
			LoanProductAction.delRedis();
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}
	
	/**
	 * 修改位置
	 */
	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void updatePosition() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String position = (String) paramsMap.get("position");
		String sql = "update loan_advert set position = ? where id = ?";
		
		try {
			if (position != null && position != "") {
				dao.update(sql, new Object[]{Integer.parseInt(position),id});
			} else {
				dao.update(sql, new Object[]{Integer.parseInt(position),id});
			}

			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "修改成功";
			result.add("result", resultJs.toJSON());
			LoanProductAction.delRedis();
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}
	

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void sortTab() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String prdidListStr = (String) paramsMap.get("prdSortList");
		String[] prdidList = prdidListStr.split("#");
		parsePageRequest();
		try {
			String sql = "update loan_advert c set c.position = ? where c.id = ?";
			for (int index = 0; index < prdidList.length; ++index) {
				Long id = Long.parseLong(prdidList[index]);
				dao.update(sql, index, id);
			}
			LoanProductAction.delRedis();
			responseSuccess();
		} catch (Exception e) {
			LogService.error(e);
			responseError(e);
		}
	}
    
	/**
	 * 排序
	 */
	public void sortPosition() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String valueindex = (String) paramsMap.get("valueindex");
		String ids = (String) paramsMap.get("ids");
		String[] idvalue = ids.split(",");
		String[] indexs = valueindex.split(",");
		parsePageRequest();
		try {
			String sql = "update loan_advert c set c.position = ? where c.id = ?";
			for (int i = 0; i < indexs.length; i++) {
				Long id = Long.parseLong(idvalue[i]);
				int index = Integer.parseInt(indexs[i]);
				dao.update(sql, index, id);
			}
			LoanProductAction.delRedis();
			responseSuccess();
		} catch (Exception e) {
			LogService.error(e);
			responseError(e);
		}
	}

	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description <p>
	 *              返回错误信息
	 *              </p>
	 *              　　　　　
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	private void loadLogCategory(String id, String name) {
		logCategorysArrayList.clear();
		ControlLogCategory logCategory = new ControlLogCategory();
		logCategory.setId(id);
		logCategory.setName(name);
		logCategorysArrayList.add(logCategory);
	}

	@Override
	public ArrayList<ControlLogCategory> getProduct() {
		return logCategorysArrayList;
	}

	public void delRedis() {
		List<String> redisList = JedisUtils.lrange("loan:activity_list", 0, -1);
		if (redisList != null && redisList.size() > 0) {
			JedisUtils.del("loan:activity_list");
		}
		if (JedisUtils.exists(LoanRedisKey.LOAN_PROXY_CREDIT_LIST)) {
			JedisUtils.del(LoanRedisKey.LOAN_PROXY_CREDIT_LIST);
		}
		responseSuccess();
	}

	/*public void updatePosition() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String id = (String) paramsMap.get("id");
		String position = (String) paramsMap.get("position");
		String sql = "update loan_advert set position= ? where id = ?";
		dao.update(sql, new Object[]{position,id});
		responseSuccess();
	}*/
	
	public void showInvest() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String str = (String) paramsMap.get("ids");
		String status = (String) paramsMap.get("status");
		String[] ids = str.split(",");
		String sql = "update loan_advert set status = ? where id =?";
		for (String id : ids) {
			if (!StringUtils.isEmpty(id)) {
				try {
					dao.update(sql, new Object[] { status, id });
				} catch (AppException e) {
					LogService.error(e);
				}
			}
		}
		responseSuccess();
	}
	
	/**
	 * 时间比较
	 * @param date1
	 * @param date2
	 * @return
	 * @throws ParseException
	 */
	public static int compareDate(String date1,String date2) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(format.parse(date1));
		Date d1 = calendar.getTime();
		calendar.setTime(format.parse(date2));
		Date d2 = calendar.getTime();
		return d1.compareTo(d2); // d1 < d2  返回 -1 , d1 > d2 返回 1 , d1 = d2 返回 0
	}
}
